package com.probiz.estoresa.content.web.action;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.validation.BindException;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.servlet.ModelAndView;

import com.probiz.estore.catalog.service.ProductCategoryManager;
import com.probiz.estore.common.model.catalog.ProductCategory;
import com.probiz.estore.common.model.content.Advertisement;
import com.probiz.estore.content.model.AdvertisementFullyModel;
import com.probiz.estore.content.service.AdPositionTypeManager;
import com.probiz.estore.content.service.AdvertisementManager;
import com.probiz.estore.core.controller.GenericStoreAdminController;
import com.probiz.estore.core.exception.ApplicationException;
import com.probiz.estore.core.model.BaseObject;
import com.probiz.estore.webapp.util.RequestUtil;

public class AdvertisementController extends GenericStoreAdminController<Advertisement> {
	private AdvertisementManager advertisementManager;
	private ProductCategoryManager productCategoryManager;
	private AdPositionTypeManager adPositionTypeManager;
	
	public void setProductCategoryManager(ProductCategoryManager productCategoryManager) {
		this.productCategoryManager = productCategoryManager;
	}
	public void setAdvertisementManager(AdvertisementManager advertisementManager) {
		this.advertisementManager = advertisementManager;
	}
	
	public void setAdPositionTypeManager(AdPositionTypeManager adPositionTypeManager) {
		this.adPositionTypeManager = adPositionTypeManager;
	}
	@Override
	protected void initController() throws Exception {
		this.mgr = advertisementManager;
		
	}
	@Override
	protected String getEntityName(Advertisement entity) {
		return entity.getAdvertisementName();
	}
	
	@Override
	protected Map<String,String> getSortMap4Direction(){
		Map<String,String> sortMap = new HashMap<String,String>();
		sortMap.put("1", "convert_gbk(advertisementName) asc");
		sortMap.put("2", "convert_gbk(advertisementName) desc");
		sortMap.put("3", "startPublishTime asc");
		sortMap.put("4", "startPublishTime desc");
		sortMap.put("5", "endPublishTime asc");
		sortMap.put("6", "endPublishTime desc");
		sortMap.put("7", "sortOrder asc");
		sortMap.put("8", "sortOrder desc");
		sortMap.put("9", "convert_gbk(adPositionType.positionName) asc");
		sortMap.put("10", "convert_gbk(adPositionType.positionName) desc");
		sortMap.put("11", "contentType asc");
		sortMap.put("12", "contentType desc");
		sortMap.put("13", "status asc");
		sortMap.put("14", "status desc");
		return sortMap;
	}
	
	@Override
	public ModelAndView multiSave(HttpServletRequest request,HttpServletResponse response) {
		String[] ids = request.getParameterValues("advertisementIds");
		String[] sortOrders = request.getParameterValues("sortOrders");
		if(ids!=null){
			for (int i = 0; i < ids.length; i++) {
				Advertisement advertisement = this.advertisementManager.getById(new Integer(ids[i]));
				try{
					if(StringUtils.isNotBlank(sortOrders[i])){
						advertisement.setSortOrder(Integer.valueOf(sortOrders[i]));
						advertisementManager.save(advertisement);
					}
				}catch(Exception e){
					e.printStackTrace();
				}
			}
		}
		return search(request,response);
	}
	
	protected void onShowForm(HttpServletRequest request, ModelAndView mv){
		mv.addObject("adPositionTypeList", adPositionTypeManager.listAllOrdered("adPositionTypeId", true));
	}
	
	/**
	 * 根据目录id获得路径全名
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ModelAndView getSimpleCategoryPathName(HttpServletRequest request,	HttpServletResponse response) throws Exception {
		Map<String, Object> data = new HashMap<String, Object>();
		ProductCategory productCategory =productCategoryManager.getById(RequestUtil.getInteger(request, "categoryId"));
		data.put("simpleCategoryPathName", productCategory.getSimpleCategoryPathName());
		data.put("categoryId", productCategory.getCategoryId());
		return getModelAndAjaxJsonView(data);
	}
	
	@Override
	public ModelAndView save(HttpServletRequest request, HttpServletResponse response) throws Exception {
		// 取得Form对应的Model
		Advertisement entity = formBackingObject(request);

		BindException errors = null;
        Map<String, Object> data = new HashMap<String, Object>();
		try {
			ServletRequestDataBinder binder = bindAndValidate(request, entity);
			errors = new BindException(binder.getBindingResult());
			// 传给子类的实现，后者可以继续验证和加入错误到errors
			preSave(request, entity, errors);
			if (!errors.hasErrors()) {// 里面如果出错应该抛出异常
				Map<String, Object> saveData = advertisementManager.saveFully(getAdvertisementFullyModel(request, entity, data));
				data.putAll(saveData);  //这里页面返回由于不是用JSON返回，所以回传的id值可以不处理。
				postSave(request, entity);
			}
		} catch (ApplicationException e) {
			handleApplicationException(errors, e);
		}

		ModelAndView mav;
		if (errors.hasErrors()) {
			mav = showForm(request, errors);
		} else if (successView != null) {
			mav = getModelAndView(successView, errors.getModel());
		} else {
			mav = getRedirectToActionView("edit", ((BaseObject) entity).getId()
					.toString());
		}
		return mav;
	}
	/**
	 * 获得保存广告的model
	 * @param request
	 * @param advertisement
	 * @param data
	 * @return
	 */
	private AdvertisementFullyModel getAdvertisementFullyModel(HttpServletRequest request, Advertisement advertisement, Map<String, Object> data) {
		AdvertisementFullyModel model = new AdvertisementFullyModel();
        model.setAdvertisement(advertisement);
		String[] categoryIds = RequestUtil.getParameterValuesNullSafe(request,"categoryIds");
		String[] isSubIncludeds = RequestUtil.getParameterValuesNullSafe(request,"isSubIncludeds");
		model.setCategoryIds(categoryIds);
        model.setIsSubIncludeds(isSubIncludeds);
        return model;
    }

}
